package com.fm.financemanage.service;




import com.fm.financemanage.constant.UserConstants;
import com.fm.financemanage.mapper.SysMenuMapper;
import com.fm.financemanage.mapper.SysRoleMenuMapper;
import com.fm.financemanage.mapper.SysUserMapper;
import com.fm.financemanage.model.po.SysMenu;
import com.fm.financemanage.model.po.SysUser;
import com.fm.financemanage.model.vo.Ztree;
import com.fm.financemanage.utils.TextUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version V1.0
 */
@Service
public class SysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";
    @Resource
    private SysMenuMapper menuMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 根据用户查询菜单
     *
     * @param user 用户信息
     * @return 菜单列表
     */

    public List<SysMenu> selectMenusByUser(SysUser user) {
        List<SysMenu> menus = new LinkedList<SysMenu>();
        // 管理员显示所有菜单信息
        if (user == null) {
            menus = menuMapper.selectMenuNormalAll();
        } else {
            menus = menuMapper.selectMenusByUserId(user.getId());
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */

    public List<SysMenu> selectMenuList(String menuName, Integer visible) {
        return menuMapper.selectMenuList(menuName, visible);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */

    public List<SysMenu> selectMenuAll(Long userId) {

        List<SysMenu> menuList = null;
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (UserConstants.SYSTEM_SUPER_USER_TYPE.equals(sysUser.getUserType())) {
            menuList = menuMapper.selectMenuAll();
        } else {
            menuList = menuMapper.selectMenuAllByUserId(userId);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */

    public Set<String> selectPermsByUserId(Long userId) {
        List<String> perms = null;
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (UserConstants.SYSTEM_SUPER_USER_TYPE.equals(sysUser.getUserType())) {
            perms = menuMapper.selectPermsAll();
        } else {
            perms = menuMapper.selectPermsByUserId(userId);
        }
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param roleId 角色id
     * @return 菜单列表
     */

    public List<Ztree> roleMenuTreeData(Long roleId, Long userId) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysMenu> menuList = menuMapper.selectMenuAll();
        if (roleId != null) {
            List<Long> roleMenuList = menuMapper.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        } else {

            ztrees = initZtree(menuList, null, true);


        }
        return ztrees;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */

    public List<Ztree> menuTreeData(Long userId) {
        List<SysMenu> menuList = selectMenuAll(userId);

        return initZtree(menuList);
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */

    public LinkedHashMap<String, String> selectPermsAll(Long userId) {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<SysMenu> permissions = selectMenuAll(userId);
        if (!TextUtil.isEmpty(permissions)) {
            for (SysMenu menu : permissions) {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList) {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList     菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysMenu> menuList, List<Long> roleMenuList, boolean permsFlag) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = !TextUtil.isEmpty(roleMenuList);
        for (SysMenu menu : menuList) {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck) {
                ztree.setChecked(roleMenuList.contains(menu.getId()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(SysMenu menu, boolean permsFlag) {
        StringBuilder sb = new StringBuilder();
        sb.append(menu.getMenuName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;").append(menu.getPerms()).append("</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */

    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 父级菜单ID
     * @return 结果
     */

    public int selectCountMenuByParentId(Long parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    public int selectCountRoleMenuByMenuId(Long menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public int insertMenu(SysMenu menu) {

        menu.setCreateTime(LocalDateTime.now());
        return menuMapper.insertSelective(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public int updateMenu(SysMenu menu) {
        return menuMapper.updateByPrimaryKeySelective(menu);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public String checkMenuNameUnique(SysMenu menu) {
        long menuId = TextUtil.isEmpty(menu.getId()) ? -1L : menu.getId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (!TextUtil.isEmpty(info) && info.getId() != menuId) {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list    菜单列表表
     * @param sysMenu 菜单对象
     */
    private void recursionFn(List<SysMenu> list, SysMenu sysMenu) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, sysMenu);
//        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        for (SysMenu n : list) {
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    public int count(String menuName, Integer visible) {
        return menuMapper.countMenuList(menuName, visible);
    }
   @Transactional(rollbackFor = Exception.class)
   public void importMenu( List<SysMenu> menus, String loginName) {
       if (menus == null || menus.size() == 0) {
           return;
       }
       List<SysMenu> childrenList = new ArrayList<>();
       // 根据父级菜单对子级分组
       Map<Long, List<SysMenu>> childrenMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getParentId));

       if (childrenMap != null) {
           // 删除角色菜单关联关系
           roleMenuMapper.removeAll();
           // 删除所有菜单
           menuMapper.removeAll();

           //先获取所有一级菜单
           List<SysMenu> oneMenus = childrenMap.get(0L);
           // parentId == 0 为 1级 菜单
           oneMenus.forEach(s->{
               // 获取 一级菜单的子级菜单
               Long old = s.getId();
               // 将一级菜单存入并返回新的id
               s.setCreateBy(loginName);
               menuMapper.insertSelective(s);
               // 把所以二级菜单的父级id进行更新
               menus.forEach(children -> {if(children.getParentId().equals(old)){
                   children.setParentId(s.getId());
               }
               });

           });
           Map<Long, List<SysMenu>> allMenusMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getId));
           childrenMap.forEach((parentId, childrens) -> {
               // 获取原本的id
               //找到对应id的菜单
               if(parentId!=0){
                   List<SysMenu> parent = allMenusMap.get(parentId);
                   if(parent==null){
                       return;
                   }
                   SysMenu sysMenu = parent.get(0);
                   // 排除一级菜单
                   if(sysMenu.getParentId()==0){
                       return;
                   }
                   // 所有子级
                   menuMapper.insertSelective(sysMenu);
                   if (childrens != null) {
                       childrens.forEach(children -> children.setParentId(sysMenu.getId()));
                       childrenList.addAll(childrens);
                   }
               }

           });
       }
       if (childrenList.size() > 0) {

           menuMapper.batchAdd(childrenList,loginName);
       }

   }


    // 导出数据
    public List<SysMenu> getAll() {
        return menuMapper.selectMenuList(null, null);
    }

}

